package top.bulk.encrypt.advice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import top.bulk.encrypt.annotation.Decrypt;
import top.bulk.encrypt.util.AnnUtil;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 解密处理类
 * <p>
 * RequestBodyAdvice 是 Spring Framework 提供的一个接口，它允许开发者在控制器方法接收到请求体数据之前，对请求体的数据进行预处理。
 * <p>
 * 这个接口可以被用来实现诸如请求参数的日志记录、解密、验证签名等功能，尤其在需要对敏感数据进行加密传输的场景下非常有用
 *
 * @author 散装java
 * @date 2024-07-18
 */
@Component
@Slf4j
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 获取参数
        Class<?> clazz = methodParameter.getNestedParameterType();
        methodParameter.hasParameterAnnotation(Decrypt.class);
        // 判断当前返回类型是否被 @Encrypt 注解
        return AnnUtil.hasAnnotation(clazz, Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        // 对需要解密的参数做解密的操作
        return null;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
